<template>
  <div class="merchant-info-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-s-shop"></i>
        商户信息管理
      </h2>
      <p class="page-description">完善您的商户信息，上传营业执照和卫生许可证</p>
    </div>

    <!-- 商户信息表单 -->
    <div class="merchant-form">
      <el-card>
        <div slot="header" class="card-header">
          <i class="el-icon-edit-outline"></i>
          <span>商户信息</span>
        </div>

        <el-form :model="form" :rules="rules" ref="form" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商户名称" prop="merchantName">
                <el-input v-model="form.merchantName" placeholder="请输入商户名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商户手机号" prop="merchantPhone">
                <el-input v-model="form.merchantPhone" placeholder="请输入商户手机号" maxlength="11"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="商户地址" prop="merchantAddress">
                <el-input v-model="form.merchantAddress" placeholder="请输入商户地址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 证件上传区域 -->
          <el-divider content-position="left">
            <i class="el-icon-upload"></i>
            <span style="margin-left: 8px;">证件上传</span>
          </el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="营业执照" prop="certificateUrl">
                <div class="upload-wrapper">
                  <el-upload
                    class="upload-container"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :on-success="handleCertificateSuccess"
                    :before-upload="beforeUpload"
                    :on-progress="(event, file) => { uploading.certificate = true }"
                    :show-file-list="false">
                    <div class="upload-area" v-if="!form.certificateUrl">
                      <i class="el-icon-plus upload-icon"></i>
                      <div class="upload-text">点击上传营业执照</div>
                      <div class="upload-tip">JPG/PNG，不超过2MB</div>
                    </div>
                    <div class="upload-preview" v-else>
                      <el-image
                        :src="getImageUrl(form.certificateUrl)"
                        fit="cover"
                        :preview-src-list="[getImageUrl(form.certificateUrl)]"
                        class="preview-image">
                        <div slot="error" class="image-slot-error">
                          <i class="el-icon-picture-outline"></i>
                          <div class="error-text">图片加载失败</div>
                        </div>
                      </el-image>
                      <div class="upload-mask" @click.stop>
                        <i class="el-icon-delete" @click.stop="form.certificateUrl = ''" title="删除图片"></i>
                      </div>
                    </div>
                  </el-upload>
                </div>
                <div class="upload-note" v-if="form.certificateUrl">
                  <i class="el-icon-success"></i>
                  <span>营业执照已上传</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="卫生许可证" prop="hygienicUrl">
                <div class="upload-wrapper">
                  <el-upload
                    class="upload-container"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :on-success="handleHygienicSuccess"
                    :before-upload="beforeUpload"
                    :on-progress="(event, file) => { uploading.hygienic = true }"
                    :show-file-list="false">
                    <div class="upload-area" v-if="!form.hygienicUrl">
                      <i class="el-icon-plus upload-icon"></i>
                      <div class="upload-text">点击上传卫生许可证</div>
                      <div class="upload-tip">JPG/PNG，不超过2MB</div>
                    </div>
                    <div class="upload-preview" v-else>
                      <el-image
                        :src="getImageUrl(form.hygienicUrl)"
                        fit="cover"
                        :preview-src-list="[getImageUrl(form.hygienicUrl)]"
                        class="preview-image">
                        <div slot="error" class="image-slot-error">
                          <i class="el-icon-picture-outline"></i>
                          <div class="error-text">图片加载失败</div>
                        </div>
                      </el-image>
                      <div class="upload-mask" @click.stop>
                        <i class="el-icon-delete" @click.stop="form.hygienicUrl = ''" title="删除图片"></i>
                      </div>
                    </div>
                  </el-upload>
                </div>
                <div class="upload-note" v-if="form.hygienicUrl">
                  <i class="el-icon-success"></i>
                  <span>卫生许可证已上传</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <div class="form-actions">
              <el-button type="primary" size="medium" @click="handleSubmit" :loading="submitting" icon="el-icon-check">
                保存信息
              </el-button>
              <el-button size="medium" @click="handleReset" icon="el-icon-refresh">
                重置表单
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { updateMerchantInfo, getMerchantInfo } from '@/api/merchant/merchant-info'
import { getToken } from '@/utils/auth'

export default {
  name: 'MerchantInfo',
  data() {
    return {
      // 表单数据
      form: {
        merchantName: '',
        merchantPhone: '',
        merchantAddress: '',
        certificateUrl: '',
        hygienicUrl: ''
      },

      // 表单验证规则
      rules: {
        merchantName: [
          { required: true, message: '请输入商户名称', trigger: 'blur' }
        ],
        merchantPhone: [
          { required: true, message: '请输入商户手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        merchantAddress: [
          { required: true, message: '请输入商户地址', trigger: 'blur' }
        ],
        certificateUrl: [
          { required: true, message: '请上传营业执照', trigger: 'change' }
        ],
        hygienicUrl: [
          { required: true, message: '请上传卫生许可证', trigger: 'change' }
        ]
      },

      // 上传相关
      uploadUrl: '/agg/file/upload',
      uploadHeaders: {},
      uploading: {
        certificate: false,
        hygienic: false
      },

      // 提交状态
      submitting: false
    }
  },

  created() {
    // 初始化上传头信息
    const token = getToken()
    if (token) {
      this.uploadHeaders['token'] = token
    }
    // 加载商户信息
    this.loadMerchantInfo()
  },

  methods: {
    // 加载商户信息
    async loadMerchantInfo() {
      try {
        Logger.log('=== 加载商户信息 ===')
        const response = await getMerchantInfo()
        Logger.log('商户信息响应:', response)

        if (response.code === 0 && response.data) {
          const data = response.data
          this.form = {
            merchantName: data.merchantName || data.name || '',
            merchantPhone: data.merchantPhone || data.phone || '',
            merchantAddress: data.merchantAddress || data.address || '',
            certificateUrl: data.certificateUrl || '',
            hygienicUrl: data.hygienicUrl || ''
          }
          Logger.log('商户信息加载成功:', this.form)
        } else {
          Logger.log('未获取到商户信息，使用默认值')
        }
      } catch (error) {
        Logger.error('加载商户信息失败:', error)
        this.$message.warning('加载商户信息失败，请重试')
      }
    },

    // 上传前验证
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }

      // 动态更新token，确保使用最新的token
      const token = getToken()
      if (token) {
        this.uploadHeaders['token'] = token
      } else {
        this.$message.error('请先登录!')
        return false
      }

      return true
    },

    // 处理图片URL - 如果是相对路径，转换为完整路径
    getImageUrl(url) {
      if (!url) return ''
      // 如果已经是完整URL（以http或https开头），直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url
      }
      // 如果是相对路径（以/开头），可能是OSS路径或本地路径，直接返回让浏览器处理
      if (url.startsWith('/')) {
        return url
      }
      // 其他情况，尝试添加/profile前缀（本地存储）
      return `/profile/${url}`
    },

    // 营业执照上传成功
    handleCertificateSuccess(response) {
      this.uploading.certificate = false
      Logger.log('营业执照上传响应:', response)
      if (response && response.code === 0) {
        // 优先使用data字段，如果没有则使用msg字段（兼容不同接口返回格式）
        const imageUrl = response.data || response.msg || ''
        if (imageUrl) {
          this.form.certificateUrl = imageUrl
          this.$message.success('营业执照上传成功')
          Logger.log('营业执照URL:', imageUrl)
        } else {
          this.$message.error('营业执照上传失败：未获取到图片URL')
        }
      } else {
        this.$message.error(response?.msg || '营业执照上传失败')
      }
    },

    // 卫生许可证上传成功
    handleHygienicSuccess(response) {
      this.uploading.hygienic = false
      Logger.log('卫生许可证上传响应:', response)
      if (response && response.code === 0) {
        // 优先使用data字段，如果没有则使用msg字段（兼容不同接口返回格式）
        const imageUrl = response.data || response.msg || ''
        if (imageUrl) {
          this.form.hygienicUrl = imageUrl
          this.$message.success('卫生许可证上传成功')
          Logger.log('卫生许可证URL:', imageUrl)
        } else {
          this.$message.error('卫生许可证上传失败：未获取到图片URL')
        }
      } else {
        this.$message.error(response?.msg || '卫生许可证上传失败')
      }
    },

    // 提交表单
    async handleSubmit() {
      try {
        // 表单验证
        await this.$refs.form.validate()

        this.submitting = true

        // 构建提交数据，兼容后端接口格式
        const submitData = {
          id: this.$store.state.user.id,
          name: this.form.merchantName,
          phone: this.form.merchantPhone,
          address: this.form.merchantAddress,
          certificateUrl: this.form.certificateUrl,
          hygienicUrl: this.form.hygienicUrl
        }

        Logger.log('=== 提交商户信息 ===')
        Logger.log('商户信息数据:', submitData)

        const response = await updateMerchantInfo(submitData)
        Logger.log('商户信息提交响应:', response)

        if (response.code === 0) {
          this.$message.success('商户信息保存成功')
          // 重新加载商户信息
          this.loadMerchantInfo()
        } else {
          this.$message.error(response.msg || '商户信息保存失败，请重试')
        }
      } catch (error) {
        Logger.error('表单验证失败或提交失败:', error)
        if (error.message) {
          this.$message.error(error.message)
        }
      } finally {
        this.submitting = false
      }
    },

    // 重置表单
    handleReset() {
      this.$refs.form.resetFields()
      this.loadMerchantInfo() // 重新加载原始数据
    }
  }
}
</script>

<style scoped>
.merchant-info-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.merchant-form {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-header i {
  margin-right: 8px;
  color: #409eff;
}

.upload-wrapper {
  width: 100%;
}

.upload-container {
  width: 100%;
}

.upload-area {
  width: 100%;
  height: 180px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fafafa;
}

.upload-area:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.upload-icon {
  font-size: 48px;
  color: #8c939d;
  margin-bottom: 12px;
}

.upload-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
}

.upload-preview {
  position: relative;
  width: 100%;
  height: 180px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.image-slot-error {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
}

.image-slot-error i {
  font-size: 48px;
  margin-bottom: 8px;
}

.error-text {
  font-size: 14px;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
}

.upload-preview:hover .upload-mask {
  opacity: 1;
}

.upload-mask i {
  font-size: 24px;
  color: #fff;
  cursor: pointer;
}

.upload-mask i:hover {
  color: #f56c6c;
}

.upload-note {
  margin-top: 8px;
  font-size: 12px;
  color: #67c23a;
  display: flex;
  align-items: center;
}

.upload-note i {
  margin-right: 4px;
}

.form-actions {
  display: flex;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .merchant-form .el-col {
    margin-bottom: 16px;
  }

  .form-actions {
    flex-direction: column;
  }

  .form-actions .el-button {
    width: 100%;
  }
}
</style>

